# cmd: python3 helper4SendEmail.py
#   --EmailTo=zhangqiming@starblink.co,tel8617706713271@163.com
#   --BuildDesc=Any-Tips
#   --JenkinsBuildDescFile=/Users/guodong/workspace1/guang-app/jenkins/jenkinsBuildDesc.tmp
#   --AndPath=/Users/guodong/workspace1/guang-app/bak/test/local/and/app-ci-release.apk.qrcode.png
# desc: 同步../pubspec.yaml版本信息到../android/guang_build.properties
import os
import json
import string
import sys
import time
import getopt

try:
    import smtplib
except ImportError:
    os.system("pip3 install secure-smtplib")
    import smtplib
else:
    pass

try:
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.mime.image import MIMEImage
    from email.header import Header
except ImportError:
    os.system("pip3 install email")
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    from email.mime.image import MIMEImage
    from email.header import Header
else:
    pass

import base64
import helperUtils as Utils

SCRIPT_DIR = os.path.dirname(__file__)
SCRIPT_NAME = os.path.basename(__file__)
_TAG = SCRIPT_NAME

EmailTo = ""
BuildDesc = ""
JenkinsBuildDescFile = ""
ApkQrcodePath = ""
IpaQrcodePath = ""

try:
    opts, args = getopt.getopt(sys.argv[1:], "hu:p:", ["help", "EmailTo=", "AndPath="
        , "BuildDesc=", "JenkinsBuildDescFile="])
except getopt.GetoptError:
    sys.exit(2)
for opt, arg in opts:
    if opt in ("-h", "--help"):
        sys.exit()
    elif opt in ("--EmailTo"):
        EmailTo = arg
    elif opt in ("--AndPath"):
        ApkQrcodePath = arg
    elif opt in ("--BuildDesc"):
        BuildDesc = arg
    elif opt in ("--JenkinsBuildDescFile"):
        JenkinsBuildDescFile = arg


def sendEmail():
    from email.mime.multipart import MIMEMultipart
    msg = MIMEMultipart('mixed')
    msg['Subject'] = "打包通知"  # 邮件主题
    msg['From'] = "anyone@starblink.co"  # 发送者账号
    msg['To'] = EmailTo  # 接收者账号列表

    final_build_desc = BuildDesc
    if os.path.exists(BuildDesc):
        final_build_desc = open(BuildDesc, 'rt').read()
        pass

    and_version_info = ""
    if ApkQrcodePath != "":
        try:
            sendimagefile = open(ApkQrcodePath, 'rb').read()
        except Exception as e:
            raise Exception('图片无法打开！！！！')
        else:
            image = MIMEImage(sendimagefile)
            image.add_header('Content-ID', '<image_ApkQrcodePath>')
            image.add_header('Content-Disposition', "attachment; filename=Android.png")
            msg.attach(image)

            build_info_json = SCRIPT_DIR + "/../android/buildInfo.json"
            version_info = ""
            if os.path.exists(build_info_json):
                version_info = open(build_info_json, "rt").read()
                version_info = "Android:<br><font color='grey'>%s</font>" % version_info
                and_version_info = version_info
                pass

    msg.attach(MIMEText("""
        <h1>Build Info:</h1>
        <h2>Build desc (developer):</h2>
        <p>%s</p>
        <hr>
        <h2>Build desc (environment):</h2>
        <p>%s</p>
        <hr>
        <h2>Git logs:</h2>
        <p>%s</p>
        <hr>
        <h2>Version Info:</h2>
        <p>%s</p><p>%s</p>
    """ % (final_build_desc, open(JenkinsBuildDescFile, 'rt').read().replace("\n", "<br>"),
           Utils.last20GitSubmit().replace("\n", "<br>"), and_version_info),
                        'html', 'utf-8'))

    try:
        # pass FOXxcTl3MxQqVPJO
        mailserver = smtplib.SMTP_SSL('smtp.feishu.cn', 465)
        # identify ourselves to smtp gmail client
        # mailserver.ehlo()
        # secure our email with tls encryption
        # mailserver.starttls()
        # re-identify ourselves as an encrypted connection
        # mailserver.ehlo()
        mailserver.login('jenkins4mobile@lershine.com', 'g432x1Fpc0AMEBgM')
        try:
            mailserver.sendmail('jenkins4mobile@lershine.com', EmailTo, msg.as_string())
        finally:
            mailserver.quit()
        Utils.log(_TAG, "Successfully sent email")
    except Exception:
        Utils.log(_TAG, "Error: unable to send email")
    pass


sendEmail()
